import Vue from 'vue'
import VueRouter from 'vue-router'

// 一级路由
import Home from '../views/Home/index.vue'
import Login from '../views/Login/index.vue'
import ChangeCity from '../views/ChangeCity'

// 缺省页
import ErrorPage from './errPage'

// 主页二级
import MainPage from './MainPage'

Vue.use(VueRouter)

const routes = [
  ...ErrorPage,
  {
    path: '/',
    name: 'Home',
    component: Home,
    children: [...MainPage]
  },
  {
    path:'/login',
    component: Login
  },
  {
    path: '/changecity',
    component: ChangeCity
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 路由拦截 如果用户未登录  统一跳到登录页面
router.beforeEach((to, from, next) => {
  // from: 当前路由信息
  // to: 目标路由信息 
  // next: 通过

  console.log(to)
  
  // 获取登录状态
  const token = localStorage.getItem('token')

  // 判断用户是否登录，如果没有登录 且跳转的不是登录页面 就重定向到登录页
  if (!token && to.path !== '/login' && !to.meta.filter) {
    // 未登录
    next('/login')
  } else {
    next()
  }
})


export default router
